package com.smarth.zhizulian.http;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.smarth.zhizulian.app.BaseConfig;
import com.smarth.zhizulian.http.inter.RetrofitService;
import com.smarth.zhizulian.http.interceptor.SecurityInterceptor;
import com.smarth.zhizulian.utils.KumaLog;
import com.smarth.zhizulian.utils.SPUtils;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by KUMA on 2017/10/8.
 */

public class KumaHttp {
    // Retrofit是基于OkHttpClient的，可以创建一个OkHttpClient进行一些配置
    private static OkHttpClient httpClient = new OkHttpClient.Builder()
            .addInterceptor(new SecurityInterceptor())
//             添加通用的Header
            .addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request.Builder builder = chain.request().newBuilder();
                    String header = SPUtils.getString(BaseConfig.SP.TOKEN, "1");
                    if ("1".equals(header)) {
                        return chain.proceed(builder.build());
                    }
                    builder.addHeader("X-Auth-Token", header);
                    return chain.proceed(builder.build());
                }
            })
            .addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    KumaLog.http(message);
                }
            }).setLevel(BaseConfig.IS_DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE))
//            .connectTimeout(BaseConfig.NetWork.CONNECT_TIMEOUT, TimeUnit.SECONDS)
//            .readTimeout(BaseConfig.NetWork.READ_TIMEOUT, TimeUnit.SECONDS)
            .build();

    private static RetrofitService retrofitService = new Retrofit.Builder()
            .baseUrl(BaseConfig.NetWork.BASE_URL)
            // 添加Gson转换器
            .addConverterFactory(GsonConverterFactory.create(buildGson()))
            // 添加Retrofit到RxJava的转换器
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(httpClient)
            .build()
            .create(RetrofitService.class);


    public static RetrofitService getService() {
        return retrofitService;
    }

    private static Gson buildGson() {
        return new GsonBuilder()
                .serializeNulls()
//                .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
                // 此处可以添加Gson 自定义TypeAdapter
//                .registerTypeAdapter(MineUserInfo.class, new UserInfoTypeAdapter())
//                .registerTypeAdapter(String.class, new StringConverter())
                .create();
    }

    private KumaHttp() {
    }

    /**
     * 实现了 序列化 接口    对为null的字段进行转换
     */
    public static class StringConverter implements JsonSerializer<String>, JsonDeserializer<String> {
        //字符串为null 转换成"",否则为字符串类型
        @Override
        public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return json.getAsJsonPrimitive().getAsString();
        }

        @Override
        public JsonElement serialize(String src, Type typeOfSrc, JsonSerializationContext context) {
            return src == null || src.equals("null") ? new JsonPrimitive("") : new JsonPrimitive(src.toString());
        }
    }
}
